package com.thinkgsp.webapp.util;

import java.io.IOException;  

import javax.servlet.Filter;  
import javax.servlet.FilterChain;  
import javax.servlet.FilterConfig;  
import javax.servlet.ServletException;  
import javax.servlet.ServletRequest;  
import javax.servlet.ServletResponse;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.WebAttributes;
import org.springframework.util.StringUtils;
  
public class ImageFilter implements Filter{  
  
    @Override  
    public void destroy() {  
        // TODO Auto-generated method stub  
          
    }  
  
    @Override  
    public void doFilter(ServletRequest arg0, ServletResponse arg1,  
            FilterChain arg2) throws IOException, ServletException {  
        // TODO Auto-generated method stub  
        HttpServletRequest request = (HttpServletRequest) arg0;    
        HttpServletResponse response = (HttpServletResponse) arg1;   
        request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION,null); 
        String yanzhengm = request.getParameter("j_captcha");  
        if(org.apache.commons.lang.StringUtils.isEmpty(yanzhengm)){
        	request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, new AuthenticationServiceException("验证码不能为空"));
        	//request.getSession().setAttribute("CHECK_CODE_ERROR","验证码不能为空");
        	response.sendRedirect(request.getContextPath()+"/login.jsp?error=true");  
        	return;
        }
        	
        String sessionyanz = (String)request.getSession(true).getAttribute(RandomValidateCode.RANDOMCODEKEY);  
        if(yanzhengm.toUpperCase().equals(sessionyanz.toUpperCase())){  
            arg2.doFilter(request, response);   
        }else{  
        	//request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", "验证码错误");
        	request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, new AuthenticationServiceException("验证码错误"));
            response.sendRedirect(request.getContextPath()+"/login.jsp?error=true");  
        }  
    }  
  
    @Override  
    public void init(FilterConfig arg0) throws ServletException {  
        // TODO Auto-generated method stub  
          
    }  
  
      
}  
